<template>
  <div class="pages">
    <div class="pageLevel" v-if="!sub">
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px" size="small">
        <div class="infon">
          <div class="infon_text">
            <span class="infon_shu"></span>
            <span class="infon_text_t"> 基础信息</span>
          </div>
        </div>
        <el-form-item label="活动名称" prop="activityName">
          <el-input style="width:250px;" v-model="formData.activityName" maxlength="15" :disabled="!canSave"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="dateRange">
          <el-date-picker :disabled="!canSave" v-model="formData.dateRange" value-format="yyyy-MM-dd HH:mm:ss" :clearable='false' format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="使用门店" prop="shopList">
          <el-button type="primary" @click="clickSelectStores()" plain :disabled="!canSave">选择门店</el-button>
        </el-form-item>
        <el-form-item label="">
          <el-table max-height="250" :data="formData.shopList" style="width: 80%">
            <el-table-column prop="name" align="center" label="门店名称"> </el-table-column>
            <el-table-column prop="shopType" align="center" label="类型" :formatter="shopType"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="deleteStore(scope.$index, formData.shopList)" :disabled="!canSave">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <div class="infon">
          <div class="infon_text">
            <span class="infon_shu"></span>
            <span class="infon_text_t"> 选择优惠券</span>
            <i class="el-icon-question" v-on:click="showTips=!showTips"></i>
            <span class="ts" v-show="showTips">拉新活动的券直接发放到会员卡包，无需领取</span>
          </div>
        </div>
        <el-form-item label="优惠券" prop="ticketList">
          <el-button type="primary" @click="clickSelectTickets()" plain :disabled="!canSave">选择优惠券</el-button>
        </el-form-item>
        <el-form-item>
          <el-table max-height="250" :data="formData.ticketList" style="width: 80%">
            <el-table-column prop="ticketType" :formatter="ticketType" align="center" label="优惠券类型"> </el-table-column>
            <el-table-column prop="ticketName" align="center" label="优惠券标题"></el-table-column>
            <el-table-column prop="ticketSubName" align="center" label="优惠券副标题"></el-table-column>
            <el-table-column prop="sendCount" align="center" label="发放数量">
              <template slot-scope="scope">
                <el-input v-show="canSave" v-model="scope.row.sendCount"></el-input>
                <span v-show="!canSave">{{scope.row.sendCount}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="validDay" align="center" label="有效期"></el-table-column>
            <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="deleteTicket(scope.$index, formData.ticketList)" :disabled="!canSave">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <div class="infon">
          <div class="infon_text">
            <span class="infon_shu"></span>
            <span class="infon_text_t">活动规则</span>
          </div>
        </div>
        <el-form-item label="活动人群">注册会员</el-form-item>
        <el-form-item label="每人限制参加">1次</el-form-item>
        <el-form-item label="领取规则" prop="receiveType">
          <el-radio v-model="formData.receiveType" label="1" :disabled="!canSave">卖家发放</el-radio>
        </el-form-item>
        <el-form-item label="触发条件" prop="activityTriggerCondition">
          <el-checkbox-group v-model="formData.activityTriggerCondition" :disabled="!canSave">
            <el-checkbox label="0" value='0'>pos端注册成功</el-checkbox><br>
            <el-checkbox label="1" value='1'>支付宝小程序注册成功</el-checkbox><br>
            <el-checkbox label="2" value='2'>婴联帮app注册成功</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="">
          <el-button v-if="canSave" type="primary" @click="saveAct('0','formData')">保存</el-button>
          <el-button v-if="canSave" type="primary" @click="saveAct('1','formData')">保存并提交审核</el-button>
        </el-form-item>
      </el-form>

      <el-dialog title="选择门店" :visible.sync="dialogStore" :closeOnClickModal='false' :closeOnPressEscape='false'>
        <div class="tableSearch">
          <el-form size="mini" label-width="50px">
            <el-row>
              <el-form-item label="区域">
                <el-input v-model="selectData.storeName" placeholder="请输入门店名称"></el-input>
              </el-form-item>
              <el-form-item label="类型">
                <el-select v-model="selectData.storeType" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="searchStore()">查询</el-button>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button @click="resetStore()">重置</el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="confirmSelectStore()">选择</el-button>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button @click="dialogStore=false">取消</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <el-table :data="tableDataDialogStore" height="300" ref="multipleTableStore" tooltip-effect="dark" highlight-current-row @selection-change="selectStore" :row-key="getRowKeysStore">
          <el-table-column type="selection" width="50" :reserve-selection="true"></el-table-column>
          <el-table-column prop="name" label="门店名称" align="center"></el-table-column>
          <el-table-column prop="shopType" :formatter="shopType" align="center" label="类型"></el-table-column>
        </el-table>
        <page-unit :pageData="pageDataStore" :func="getStore"></page-unit>
      </el-dialog>

      <!-- 优惠券弹窗 -->
      <el-dialog title="选择优惠券" :visible.sync="dialogTicket" :closeOnClickModal='false' :closeOnPressEscape='false'>
        <div class="tableSearch">
          <el-form size="mini">
            <el-row>
              <el-form-item label="优惠券名称" label-width="100px">
                <el-input v-model="selectData.ticketName" placeholder="请输入优惠券名称"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="searchTicket()">查询</el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="confirmSelectTicket()">选择</el-button>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button @click="dialogTicket=false">取消</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <el-table :data="tableDataDialogTicket" height="300" ref="multipleTableTicket" tooltip-effect="dark" highlight-current-row @selection-change="selectTicket" :row-key="getRowKeysTicket">
          <el-table-column type="selection" width="50" :reserve-selection="true"></el-table-column>
          <el-table-column prop="ticketName" label="优惠券标题" align="center"></el-table-column>
          <el-table-column prop="ticketSubName" label="优惠券副标题" align="center"></el-table-column>
          <el-table-column prop="ticketType" :formatter="ticketType" align="center" label="优惠券类型"></el-table-column>
          <el-table-column prop="validDay" label="有效期时间" align="center"></el-table-column>
          <el-table-column prop="ticketState" :formatter="cardStutas" label="状态" align="center"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        </el-table>
        <page-unit :pageData="pageDataTicket" :func="getCard"></page-unit>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import {
  saveOrUpdateActivity,
  updateActivity,
  selectBaseShopPageList,
  findMarketTicketListPage,
  getActivityDetail,
  findMsgTemplateListPage
} from "@/api";
import util from "@/util";
import state from "@/util/state";
export default {
  computed: mapState([
    "pageLevel",
    "merchantId",
    "sub",
    "userInfo",
    "linkName"
  ]),
  components: { pageUnit },
  data() {
    return {
      getRowKeysStore(row) {
        return row.id;
      },
      getRowKeysTicket(row) {
        return row.id;
      },
      shopType: state.shopType,
      ticketType: state.ticketType,
      cardStutas: state.cardStutas,
      canSave: false, // 是否显示保存按钮
      tableDataDialogTicket: [], // 优惠券弹窗数组
      tableDataDialogStore: [], // 弹窗门店数组
      showTips: false, // 是否显示优惠券提示
      dialogTicket: false, // 优惠券弹窗
      dialogStore: false, // 门店弹窗
      mutableStore: [], // 多选选择门店存入的数组
      mutableTicket: [], // 多选选择优惠券存入的数组
      formData: {
        id: "",
        activityName: "", //活动名称
        activityType: "1", //活动类型，0-会员拉新，1-会员关怀
        dateRange: [], // 活动时间
        activityStartTime: "", //活动开始时间
        activityEndTime: "", //活动结束时间
        shopList: [], // 使用门店
        ticketList: [], // 使用优惠券
        activityTriggerCondition: [], //0-POS注册 1-支付宝小程序注册 2-婴联邦注册
        activityCreater: "", //活动创建人
        activityAuditState: "", //活动审核状态，0-已保存 1-待审核，2-审核通过，3-审核驳回，4-已撤回;
        activityState: "", //活动状态，0-未开始，1-已开始，2-已结束
        activityCrowd: "1", //活动人群，0-全部会员，1-注册会员，2-会员等级，3-自定义会员
        maxTimes: "", //最大参与次数
        receiveType: "1" //领取规则：0-买家领取，1-卖家发放
      },
      rules: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 1, max: 25, message: "长度在 1 到 25 个字符", trigger: "blur" }
        ],
        shopList: [{ required: true, message: "请选择门店", trigger: "blur" }],
        ticketList: [
          { required: true, message: "请选择优惠券", trigger: "blur" }
        ],
        activityTriggerCondition: [
          { required: true, message: "请选择触发条件" }
        ],
        dateRange: [
          { required: true, message: "请选择活动日期", trigger: "blur" }
        ]
      },
      options: [
        // 门店类型
        { value: "", label: "全部" },
        { value: "0", label: "直营店" },
        { value: "1", label: "加盟店" }
      ],
      pageDataTicket: {
        pageSize: 5,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataStore: {
        pageSize: 5,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      selectData: {
        storeName: "", // 门店名称
        storeType: "", // 门店类型
        ticketName: ""
      }
    };
  },
  mounted() {
    let id = util.getQuery().id;
    if (
      util.getQuery().id !== "" &&
      util.getQuery().id !== null &&
      util.getQuery().id !== undefined
    ) {
      if (util.getQuery().showTab == "0") {
        // 查看
        this.canSave = false;
        this.details();
      } else if (util.getQuery().showTab == "1") {
        // 编辑
        this.canSave = true;
        this.details();
      } else {
        this.canSave = true;
      }
    } else {
      // 新增
      this.canSave = true;
    }
  },
  methods: {
    //查询门店
    getStore(pageSize, pageNum) {
      let data = {
        nameOrCode: this.selectData.storeName,
        shopType: this.selectData.storeType,
        pageNum: pageNum,
        pageSize: pageSize,
        openAccount: "", // 是否开户，0-否，1-是
        businessId: this.merchantId,
        type: 3 //1供应商（查找客户） 2-客户（查找供应商） 3-连锁（查客户）
      };
      selectBaseShopPageList(data).then(res => {
        if (res.code == 200) {
          this.tableDataDialogStore = res.data.list;
          this.pageDataStore.totalItems = res.data.pageTotal;
        }
      });
    },
    // 查询可用优惠券体验券
    getCard(pageSizec, pageNumc) {
      let data = {
        pageSize: pageSizec,
        pageNo: pageNumc,
        orgId: this.merchantId,
        ticketTypeList: "0,1",
        ticketState: 0,
        activityStartTime: this.formData.dateRange[0],
        activityEndTime: this.formData.dateRange[1],
        ticketName: this.selectData.ticketName
      };
      findMarketTicketListPage(data).then(res => {
        if (res.code == 200) {
          res.data.list.forEach(element => {
            element.sendCount = "";
          });
          this.tableDataDialogTicket = res.data.list;
          this.pageDataTicket.totalItems = res.data.totalPage;
        }
      });
    },
    // 删除一条选择的优惠券
    deleteTicket(index, rows) {
      rows.splice(index, 1);
    },
    // 删除一条选择的门店
    deleteStore(index, rows) {
      rows.splice(index, 1);
    },
    // 点击选择门店
    clickSelectStores() {
      this.getStore(this.pageDataStore.pageSize, 1);
      this.dialogStore = true;
    },
    // 点击选择优惠券
    clickSelectTickets() {
      if (this.formData.dateRange[0] == null) {
        this.$message.warning("请选择活动时间");
        return false;
      } else {
        this.getCard(this.pageDataTicket.pageSize, 1);
        this.dialogTicket = true;
      }
    },
    // 弹窗中门店多选
    selectStore(val) {
      this.mutableStore = val;
    },
    // 弹窗多选优惠券
    selectTicket(val) {
      this.mutableTicket = val;
    },
    // 弹窗门店里面的查询
    searchStore() {
      this.getStore(this.pageDataStore.pageSize, 1);
    },
    // 弹窗门店查询的重置
    resetStore() {
      this.selectData.storeName = "";
      this.selectData.storeType = "";
    },
    searchTicket() {
      this.getCard(this.pageDataTicket.pageSize, 1);
    },
    // 弹窗里确定选择门店弹窗
    confirmSelectStore() {
      if (this.mutableStore.length === 0) {
        this.$message.error("请先选择门店");
        return false;
      }
      this.formData.shopList = this.formData.shopList.concat(this.mutableStore);
      for (let i = 0; i < this.formData.shopList.length - 1; i++) {
        for (let j = i + 1; j < this.formData.shopList.length; j++) {
          if (this.formData.shopList[i].id == this.formData.shopList[j].id) {
            this.formData.shopList.splice(j, 1);
          }
        }
      }
      this.$refs.multipleTableStore.clearSelection();
      this.dialogStore = false;
    },
    // 弹窗确定选择优惠券
    confirmSelectTicket() {
      if (this.mutableTicket.length === 0) {
        this.$message.error("请先选择优惠券");
        return false;
      }
      this.formData.ticketList = this.formData.ticketList.concat(
        this.mutableTicket
      );
      for (let i = 0; i < this.formData.ticketList.length - 1; i++) {
        for (let j = i + 1; j < this.formData.ticketList.length; j++) {
          if (
            this.formData.ticketList[i].id == this.formData.ticketList[j].id
          ) {
            this.formData.ticketList.splice(j, 1);
          }
        }
      }
      this.$refs.multipleTableTicket.clearSelection();
      this.dialogTicket = false;
    },
    //保存拉新活动
    saveAct(state, formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {};
          let dateStart = new Date(this.formData.dateRange[0]).getTime();
          let dateEnd = new Date(this.formData.dateRange[1]).getTime();
          let dateCur = new Date().getTime();
          if (dateCur > dateEnd) {
            // 当前时间大于活动结束时间
            this.$message.error("活动结束时间不能小于当前时间！");
            return;
          }
          data.orgId = this.merchantId;
          data.activityName = this.formData.activityName;
          data.activityStartTime = this.formData.dateRange[0]; //活动开始时间
          data.activityEndTime = this.formData.dateRange[1]; //活动结束时间
          if (this.linkName !== "" || this.linkName !== null) {
            data.activityCreater = this.linkName; //活动创建人
          } else {
            data.activityCreater = this.userInfo.mobile; //活动创建人
          }
          data.activityAuditState = state; //活动审核状态，0-已保存 1-待审核，2-审核通过，3-审核驳回，4-已撤回;
          data.activityState = "0"; //活动状态，0-未开始，1-已开始，2-已结束
          data.activityCrowd = "1"; //活动人群，0-全部会员，1-注册会员，2-会员等级，3-自定义会员
          data.maxTimes = "1"; //最大参与次数
          data.activityType = "0"; //会员拉新
          data.activityTriggerCondition = JSON.stringify(
            this.formData.activityTriggerCondition
          ); //0-POS注册 1-支付宝小程序注册 2-婴联邦注册
          data.receiveType = "1"; //领取规则：0-买家领取，1-卖家发放
          for (var i = 0; i < this.formData.shopList.length; i++) {
            this.formData.shopList[i].orgId = this.formData.shopList[i].id;
          }
          data.shopList = JSON.stringify(this.formData.shopList);
          for (var i = 0; i < this.formData.ticketList.length; i++) {
            this.formData.ticketList[i].ticketId = this.formData.ticketList[
              i
            ].id;
          }
          data.ticketList = JSON.stringify(this.formData.ticketList);
          if (util.getQuery().id !== undefined) {
            data.id = util.getQuery().id;
            updateActivity(data).then(res => {
              if (res.code == "200") {
                util.routerTo(
                  "/marketing-center/company-active/activity-query"
                );
              }
            });
          } else {
            saveOrUpdateActivity(data).then(res => {
              if (res.code == "200") {
                util.routerTo(
                  "/marketing-center/company-active/activity-query"
                );
              }
            });
          }
        } else {
          this.$message.error("请检查必填信息");
          return false;
        }
      });
    },
    //查询详情
    details(id) {
      let data = {
        id: util.getQuery().id
      };
      if (util.getQuery().id !== undefined) {
        getActivityDetail(data).then(res => {
          if (res.code == 200) {
            this.formData = res.data;
            let dateRangeArr = [];
            dateRangeArr.push(
              util.getdatetime(this.formData.activityStartTime)
            );
            dateRangeArr.push(util.getdatetime(this.formData.activityEndTime));
            this.$set(this.formData, "dateRange", dateRangeArr);
            this.formData.receiveType = this.formData.receiveType.toString();
            this.formData.activityTriggerCondition = JSON.parse(
              res.data.activityTriggerCondition
            );
          }
        });
      }
    }
  }
};
</script>
<style scoped>
.infon_text_t {
  margin-right: 10px;
}
.ts {
  color: #909399;
}
.sub {
  margin-top: 30px;
  width: 100%;
  text-align: center;
  margin-bottom: 100px;
}
</style>
